package com.goodsogood.union.auth.sync;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.goodsogood.union.auth.conf.CommonConfiger;

/**
 * 单位信息同步器
 *
 * @author liuy
 */
@Component
public class PwdValidator {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    static final String validatePwdUrl = CommonConfiger.getInstance().getHost() + "/union/syn/user/validatePwd";
    public boolean check(String account, String pwd) {
        try {
            String para = " {\n" +
                    "            \"account\": \"" + account + "\",\n" +
                    "            \"password\": \"" + pwd + "\",\n" +
                    "        }";
            Map<String, String> params = new HashMap<>();
            params.put("para", para);
            
            logger.info("PwdValidator.check para is {}", params);
            
            String response = HttpRequest.post(
                    validatePwdUrl,
                    params, true).body();
            
            logger.info("PwdValidator.check response is {}", response);
            
            JSONObject json = JSON.parseObject(response);
            if (StringUtils.isEmpty(json.getString("data"))) {
                return false;
            }
            String data = json.getString("data");
            JSONObject dataJson = JSON.parseObject(data);
            if (dataJson == null || !dataJson.containsKey("infResult")) {
                return false;
            }
            dataJson = JSON.parseObject(dataJson.getString("infResult"));
            if (dataJson.getInteger("status") != 1) {
                return false;
            }
            JSONObject innerData = dataJson.getJSONObject("data");
            if (innerData.getInteger("validate") != 1) {
                return false;
            }
            return true;
        } catch (Exception e){
            logger.error("PwdValidator.check account is {}, happen error ", account, e);
            return false;
        }

    }
}
